package com.ranchuanyin.schoolcat.util;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

@Component
public class MinioUtil {
    @Resource
    MinioClient minioClient;
    @Value("${minio.showUrl}")
    private String showUrl;

    private static String getFileType(String filePath) {
        // 获取文件名中最后一个点的位置
        int lastDotIndex = filePath.lastIndexOf('.');

        // 检查是否找到了点
        if (lastDotIndex != -1) {
            // 使用substring方法提取文件类型（扩展名）
            return filePath.substring(lastDotIndex + 1).toLowerCase();
        } else {
            return null; // 如果没有找到点，则无法确定文件类型
        }
    }

    public String upload(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream();) {
            String fileType = getFileType(Objects.requireNonNull(file.getOriginalFilename()));
            String string = UUID.randomUUID().toString();
            String fileName = "/message/" + string + "." + fileType;
            PutObjectArgs image = PutObjectArgs.builder()
                    .bucket("image")
                    .object(fileName)
                    .stream(inputStream, file.getSize(), -1)
                    .build();
            minioClient.putObject(image);
            return showUrl + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
